//
//  LocationService.swift
//  amap
//
//  Created by James Karl on 2020/6/21.
//

import Foundation
import AMapLocationKit


class LocationService: NSObject, AMapLocationManagerDelegate {
    static let shared = LocationService()
    
    let locationManager: AMapLocationManager
    
    override private init() {
        locationManager = AMapLocationManager()
        super.init()
        locationManager.delegate = self
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.allowsBackgroundLocationUpdates = false
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        //locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    }
    
    private func checkPermission() -> String? {
        if CLLocationManager.locationServicesEnabled() == false {
            return "定位被限制，请检查设备"
        }
        
        let authStatus = CLLocationManager.authorizationStatus()
        if (CLLocationManager.locationServicesEnabled()
            && (authStatus == .authorizedAlways
                || authStatus == .authorizedWhenInUse
                || authStatus == .notDetermined)) {
            return nil
        } else if authStatus == .denied{
            return "请前往设置开启定位服务"
        } else {
            return "定位被限制，请检查设备"
        }
    }
    
    func startSerialLocation() {
        let error = checkPermission()
        if  error == nil{
            locationManager.stopUpdatingLocation()
        } else {
            print(error!)
        }
    }
    
    func stopSerialLocation() {
        locationManager.stopUpdatingLocation()
    }
    
    func requestLocation(callback: AMapLocatingCompletionBlock?) {
        locationManager.requestLocation(withReGeocode: true, completionBlock: callback)
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didFailWithError error: Error!) {
        if let locateError = error {
            print(locateError)
        }
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
        if let position = location {
            print(position)
        }
        if let info = reGeocode {
            print(info)
        }
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!) {
        if let position = location {
            print(position)
        }
    }
}
